/**
 * Created by a1 on 2017/5/25.
 */
var fs = require('fs');
var path = require('path');
var formidable = require('formidable');
var md5 = require('../models/md5');
var UsernameModel = require('../models/Username');
var UserinfoModel = require('../models/Userinfo');
const common=require('../models/common.js');
var BookshelfModel=require('../models/Bookshelf.js');
var svgCaptcha = require('svg-captcha');

exports.register=function(req,res,next){
    if(req.session.username){
        res.redirect('/user');
    }else{
        res.render('register',{
            page:'register'
        });
    }
}
exports.doReg=function(req,res){
    var form = new formidable.IncomingForm();//创建表单
    form.parse(req,function(err,fields,files){
        let {username,email,password}=fields;
        UsernameModel.findFn({},function(err,result){
            if(result==""||result==null||result==undefined){
                var md5psw = md5(md5('123456').substring(0,9)+md5('123456'));
                //初始化数据用户
                let obj={
                    uid:1,
                    username:'suwenhao',
                    payPassword:md5psw,
                    password:md5psw,
                    email:'1057607246@qq.com'
                };
                var user=new UsernameModel(obj);
                let info=new UserinfoModel({ "uiid":1,"uid":1,"nickname":"书友"+common.getTimes(new Date().getTime(),"NONE"),"month":0,"recomm":{"nan":0,"nv":0},"account":0,"away":0,"userLevel":1,"expLevel":0,"level":0,"desc":"暂无用户简介"});
                user.save();
                info.save();
            }else{
                for(var i=0;i<result.length;i++){
                    if(result[i]['username']==username){
                        res.json({code:0,retMsg:'用户名已注册'});
                        return;
                    }else if(result[i]['email']==email){
                        res.json({code:2,retMsg:'邮箱已注册'});
                        return;
                    }
                }
                UsernameModel.findSortOne({},{uid:-1},function(err,docs){
                    var md5psw = md5(md5(password).substring(0,9)+md5(password));
                    let obj={
                        uid:parseInt(docs.uid)+1,
                        username:username,
                        payPassword:md5psw,
                        password:md5psw,
                        email:email
                    };
                    let user=new UsernameModel(obj);
                    user.save(function(err){
                        if(err){
                            console.log('数据库操作出错');
                            res.json({code:3,retMsg:'数据库操作出错'});
                        }
                        let info=new UserinfoModel({ "uiid":parseInt(docs.uid)+1,"uid":parseInt(docs.uid)+1,"nickname":"书友"+common.getTimes(new Date().getTime(),"NONE"),"month":0,"recomm":{"nan":0,"nv":0},"account":0,"away":0,"userLevel":1,"expLevel":0,"level":0,"desc":"暂无用户简介"});
                        info.save(function(err){
                            if(err){
                                console.log('数据库操作出错');
                                res.json({code:3,retMsg:'数据库操作出错'});
                            }
                            BookshelfModel.findFn({},{'bsid':1},function(err,ddos) {
                                if (err) {
                                    res.json({"msg": '失败', "code": 0, info: {}});
                                    return;
                                }
                                if (ddos.length == 0) {
                                    let bsm = new BookshelfModel({
                                        "bsid": 1,
                                        "uid": parseInt(docs.uid)+1,
                                        "bookshelf": [
                                            {
                                                "sjid": 1,
                                                "sjname": "默认书架",
                                                "books": []
                                            }
                                        ]
                                    });
                                    bsm.save(function(err){
                                        res.json({code:1,retMsg:'成功注册'});
                                    });
                                }else{
                                    BookshelfModel.findSortOne({},{'bsid':-1},function(err,ddos1) {
                                        let bsm = new BookshelfModel({
                                            "bsid": parseInt(ddos1['bsid'])+1,
                                            "uid": parseInt(docs.uid)+1,
                                            "bookshelf": [
                                                {
                                                    "sjid": 1,
                                                    "sjname": "默认书架",
                                                    "books": []
                                                }
                                            ]
                                        });
                                        bsm.save(function(err){
                                            //mail(username,password,email,parseInt(docs.uid)+1);
                                            console.log('成功注册');
                                            res.json({code:1,retMsg:'成功注册'});
                                        });
                                    });
                                }
                            });
                        });

                    });
                });
            }
        })
    })
};
exports.recode=function(req,res){
    var captcha = svgCaptcha.create();
	req.session.captcha = captcha.text;
	
	res.type('svg');
	res.status(200).send(captcha.data);
};
exports.doRecode=function(req,res){
    var form = new formidable.IncomingForm();//创建表单
    form.parse(req,function(err,fields,files){
        if(fields.code.toLocaleLowerCase()==req.session.captcha.toLocaleLowerCase()){
            res.json({code:1});
        }else{
            res.json({code:0});
        }
    });
};